package com.krtech.wecard.module.ramble.task;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.module.ramble.entity.RambleDrawChance;
import com.krtech.wecard.module.ramble.entity.RambleDrawLog;
import com.krtech.wecard.module.ramble.entity.RambleLeaderboard;
import com.krtech.wecard.module.ramble.entity.RambleLoginLog;
import com.krtech.wecard.module.ramble.enums.RambleEnums;
import com.krtech.wecard.module.ramble.mapper.RambleDrawLogMapper;
import com.krtech.wecard.module.ramble.mapper.RambleLoginLogMapper;
import com.krtech.wecard.module.ramble.service.RambleDrawChanceService;
import com.krtech.wecard.module.ramble.service.RambleLeaderboardService;
import com.krtech.wecard.module.ramble.service.RambleLoginLogService;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import com.krtech.wecard.module.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class RambleLeaderboardTask {

    @Autowired
    private RambleLeaderboardService leaderboardService;

    @Autowired
    private RambleLoginLogService loginLogService;

    @Autowired
    private RambleLoginLogMapper loginLogMapper;

    @Autowired
    private RambleDrawChanceService drawChanceService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private RambleDrawLogMapper drawLogMapper;

    @Autowired
    private SysKeyValueService keyValueService;

    /**
     * 定时任务，每小时更新一下排行榜
     */
    @Scheduled(cron = "0 0/60 * * * ?")
//    @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(cron = "0 40 23 ? * *")
    public void ramble(){
        log.info("定时任务，每小时更新一下排行榜");
        //查询环境变量
        SysKeyValue stepKeyValue = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, RambleEnums.STEP));

        if (stepKeyValue == null){
            throw new BusinessException("环境变量step未配置，请联系管理员");
        }

        int step = Integer.parseInt(stepKeyValue.getSysValue());

        List<String> allUserPhone = loginLogMapper.getAllUserPhone();
        for (String phone:allUserPhone){
            try {
                analyze(phone,step);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public boolean analyze(String phone,int step){
        //判断当前是否有，如果有，则更新
        RambleLeaderboard leaderboard = leaderboardService.getOne(new QueryWrapper<RambleLeaderboard>().eq(RambleLeaderboard.COL_PHONE, phone));
        if (leaderboard == null){
            RambleLeaderboard rambleLeaderboard = new RambleLeaderboard();

            //查看抽奖次数
            //计算次数，至少得大于等于步数
            RambleDrawChance drawChance = drawChanceService.getOne(new QueryWrapper<RambleDrawChance>().eq(RambleDrawChance.COL_PHONE, phone));
            rambleLeaderboard.setDrawChance(drawChance.getDrawChance());

            //计算全部步数
            int totalStep = 0;
            List<RambleLoginLog> loginLogList = loginLogService.list(new QueryWrapper<RambleLoginLog>().eq(RambleLoginLog.COL_PHONE, phone));
            if (loginLogList.size() > 0){
                int sumStep = loginLogList.stream().mapToInt(RambleLoginLog::getStepNumber).sum();
                totalStep = sumStep;

                //判断抽奖次数
                int chance = sumStep / step;
                if (rambleLeaderboard.getDrawChance() < chance){
                    rambleLeaderboard.setDrawChance(chance);
                }
            }
            rambleLeaderboard.setTotalStep(totalStep);

            //计算昨天步数
            int yesterdayStep = 0;
            List<RambleLoginLog> yesterdayLoginLogList = loginLogService.list(new QueryWrapper<RambleLoginLog>().eq(RambleLoginLog.COL_PHONE, phone)
                    .eq(RambleLoginLog.COL_RIGISTER_DATE, DateUtil.parseDate(DateUtil.yesterday().toString())));
            if (yesterdayLoginLogList.size() > 0){
                int sumYesterdayStep = yesterdayLoginLogList.stream().mapToInt(RambleLoginLog::getStepNumber).sum();
                yesterdayStep = sumYesterdayStep;
            }
            rambleLeaderboard.setYesterdayStep(yesterdayStep);

            //放置用户信息
            SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq(SysUser.COL_PHONE, phone));
            rambleLeaderboard.setUpdatedTime(new Date());
            rambleLeaderboard.setNickName(user.getNickName());
            rambleLeaderboard.setOpenId(user.getMipOpenId());
            rambleLeaderboard.setPhone(phone);
            log.info(phone+",排行榜更新完成");
            return leaderboardService.save(rambleLeaderboard);
        }else {
            //计算全部步数
            int totalStep = 0;
            List<RambleLoginLog> loginLogList = loginLogService.list(new QueryWrapper<RambleLoginLog>().eq(RambleLoginLog.COL_PHONE, phone));
            if (loginLogList.size() > 0){
                int sumStep = loginLogList.stream().mapToInt(RambleLoginLog::getStepNumber).sum();
                totalStep = sumStep;

                //判断抽奖次数
                int chance = sumStep / step;
                if (leaderboard.getDrawChance() < chance){
                    leaderboard.setDrawChance(chance);
                }
            }
            leaderboard.setTotalStep(totalStep);

            //计算昨天步数
            int yesterdayStep = 0;
            List<RambleLoginLog> yesterdayLoginLogList = loginLogService.list(new QueryWrapper<RambleLoginLog>().eq(RambleLoginLog.COL_PHONE, phone)
                    .eq(RambleLoginLog.COL_RIGISTER_DATE, DateUtil.parseDate(DateUtil.yesterday().toString())));
            if (yesterdayLoginLogList.size() > 0){
                int sumYesterdayStep = yesterdayLoginLogList.stream().mapToInt(RambleLoginLog::getStepNumber).sum();
                yesterdayStep = sumYesterdayStep;
            }
            leaderboard.setYesterdayStep(yesterdayStep);

            //查看抽奖次数
            RambleDrawChance drawChance = drawChanceService.getOne(new QueryWrapper<RambleDrawChance>().eq(RambleDrawChance.COL_PHONE, phone));
//            leaderboard.setDrawChance(drawChance.getDrawChance());
            return leaderboardService.updateById(leaderboard);
        }
    }
}